<template>
  <BaseContainer>
    <QueryFilter class="query-filter" :model="queryFields" @submit="queryPlanList" @reset="resetPlanList">
      <a-form-item name="name" label="客户名称">
        <a-input v-model:value.trim="queryFields.name" placeholder="请输入客户名称" allow-clear />
      </a-form-item>
      <a-form-item name="proxyId" label="代理商ID">
        <a-input v-model:value.trim="queryFields.proxyId" placeholder="请输入代理商ID" allow-clear />
      </a-form-item>
      <a-form-item name="bxProxyId" label="客户百姓网UID">
        <a-input v-model:value.trim="queryFields.bxProxyId" placeholder="请输入客户百姓网UID" allow-clear />
      </a-form-item>
    </QueryFilter>
    <Divider />
    <table-toolbar title="账号列表">
      <a-button type="primary" @click="handleCreateAccount">
        <template #icon><plus-outlined /></template>
        创建关联账号
      </a-button>
    </table-toolbar>
    <a-table
      row-key="id"
      :pagination="pagination"
      :loading="loading"
      :columns="columns"
      :data-source="tableData"
      :scroll="{ x: 1000 }"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'operate'">
          <a-button type="primary" class="mr-2" @click="handleAccountEdit(record)">编辑</a-button>
          <a-popconfirm title="确定要删除吗？" @confirm="handleAccountRemove(record)">
            <a-button danger type="default">删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    <account-updater
      v-model:show="dialog.show"
      v-model:data="formFields"
      :mode="dialog.mode"
      :submitting="submitting"
      @on-submit="handleSubmitAccount"
    />
  </BaseContainer>
</template>

<script lang="ts" setup>
import TableToolbar from '@/components/table-toolbar/index.vue'
import { onMounted, reactive, ref } from 'vue'
import type { TableProps } from 'ant-design-vue'
import { formatDate } from '@/utils'
import AccountUpdater from '@/views/account/components/AccountUpdater.vue'
import delBaixingAccount from '@/services/account-management/delBaixingAccount'
import getBaixingAccount from '@/services/account-management/getBaixingAccount'
import type { BaixingAccount } from '@/services/account-management/getBaixingAccount'
import updateBaixingAccount from '@/services/account-management/updateBaixingAccount'
import type { BaixingAccountParams } from '@/services/account-management/updateBaixingAccount'
import { pick } from 'lodash-es'
import { PlusOutlined } from '@ant-design/icons-vue'
import QueryFilter from '@/components/query-filter/index.vue'
import BaseContainer from '@/components/base-container/index.vue'
import Divider from '@/components/divider/index.vue'
import { Mode } from '@/core/interfaces/common'

const defaultQueryFields = () => ({
  name: '',
  proxyId: undefined,
  bxProxyId: undefined
})
const defaultFormFields = () => ({
  id: undefined,
  name: '',
  proxyId: undefined,
  bxProxyId: undefined
})
const formFields = ref<BaixingAccountParams>(defaultFormFields())
const queryFields = reactive(defaultQueryFields())

const dialog = reactive({
  show: false,
  mode: Mode.create
})

const columns: TableProps['columns'] = [
  {
    title: 'id',
    dataIndex: 'id',
    key: 'id'
  },
  {
    title: '代理商ID',
    dataIndex: 'proxyId',
    key: 'proxyId'
  },
  {
    title: '客户百姓网UID',
    dataIndex: 'bxProxyId',
    key: 'bxProxyId'
  },
  {
    title: '客户名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '创建日期',
    dataIndex: 'createTime',
    key: 'createTime',
    customRender: ({ text }) => {
      return formatDate(text)
    }
  },
  {
    title: '操作',
    dataIndex: 'operate',
    key: 'operate',
    width: '160px'
  }
]

const tableData = ref<BaixingAccount[]>([])

const [, fetchBaixingAccount, loading] = getBaixingAccount()
const [, removeBaixingAccount] = delBaixingAccount()
const [, submitBaixingAccount, submitting] = updateBaixingAccount()

const pagination = reactive({
  current: 1,
  pageSize: 15,
  total: 0
})

function handleTableChange(pag: { pageSize: number; current: number }) {
  pagination.pageSize = pag.pageSize
  pagination.current = pag.current
  loadBaixingAccount()
}

function resetPlanList() {
  Object.assign(queryFields, defaultQueryFields())
  pagination.pageSize = 15
  pagination.current = 1
  loadBaixingAccount()
}

function queryPlanList() {
  pagination.pageSize = 15
  pagination.current = 1
  loadBaixingAccount()
}

function handleAccountEdit(record: BaixingAccount) {
  dialog.show = true
  dialog.mode = Mode.edit
  formFields.value = Object.assign(defaultFormFields(), pick(record, Object.keys(formFields.value)))
}

function handleCreateAccount() {
  dialog.show = true
  dialog.mode = Mode.create
  Object.assign(formFields, defaultFormFields())
}

async function handleAccountRemove(record: BaixingAccount) {
  const [err] = await removeBaixingAccount({
    id: record.id
  })

  if (!err) {
    await loadBaixingAccount()
  }
}

async function handleSubmitAccount() {
  const [err] = await submitBaixingAccount(formFields.value, dialog.mode)

  if (!err) {
    dialog.show = false
    await loadBaixingAccount()
  }
}

async function loadBaixingAccount() {
  const [err, res] = await fetchBaixingAccount({
    bxProxyId: queryFields.bxProxyId ?? 0,
    proxyId: queryFields.proxyId ?? 0,
    name: queryFields.name,
    pageSize: pagination.pageSize,
    pageNum: pagination.current
  })

  if (!err) {
    tableData.value = res.data.data.bxAccounts
    pagination.total = res.data.data.totalSize
  }
}
// 
// 
onMounted(() => {
  loadBaixingAccount()
})
</script>

<script lang="ts">
export default {
  name: 'AccountManagement'
}
</script>

<style lang="scss" scoped></style>
